package com.cjd.common.utils

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.security.MessageDigest

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/9/27
 * description
 */
object PackageManagerUtil {

    /**
     * 获取已安装的app
     */
    fun getInstalledApps(context: Context): List<ApplicationInfo> {
        return context.packageManager.getInstalledApplications(0)
    }

    /**
     * 判断系统应用
     */
    fun isSystemApp(applicationInfo: ApplicationInfo): Boolean {
        return applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
    }


    fun isSystemUpdateApp(applicationInfo: ApplicationInfo): Boolean {
        return applicationInfo.flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP != 0
    }

    /**
     * 判断 非系统应用
     */
    fun isUserApp(applicationInfo: ApplicationInfo): Boolean {
        return !isSystemApp(applicationInfo) && !isSystemUpdateApp(applicationInfo)
    }

    /**
     * 获取app icon
     */
    fun getIconDrawable(context: Context, packageName: String): Drawable? {
        var drawable: Drawable? = null
        var info: PackageInfo? = null
        try {
            info = context.packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
            if (info?.applicationInfo != null)
                drawable = info.applicationInfo.loadIcon(context.packageManager)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return drawable
    }

    /**
     * 获取 文件 sha1
     */
    fun fileToSHA1(filePath: String): String? {
        var inputStream: InputStream? = null
        try {
            inputStream =
                FileInputStream(filePath) // Create an FileInputStream instance according to the filepath
            val buffer = ByteArray(1024) // The buffer to read the file
            val digest = MessageDigest.getInstance("SHA-1") // Get a SHA-1 instance
            var numRead = 0 // Record how many bytes have been read
            while (numRead != -1) {
                numRead = inputStream.read(buffer)
                if (numRead > 0)
                    digest.update(buffer, 0, numRead) // Update the digest
            }
            val sha1Bytes = digest.digest() // Complete the hash computing
            return toHex(sha1Bytes) // Call the function to convert to hex digits
        } catch (e: Exception) {
            return null
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close() // Close the InputStream
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
        }
    }

    /**
     * 转换
     */
    fun toHex(byteArray: ByteArray): String {
        val result = with(StringBuilder()) {
            byteArray.forEach {
                val hex = it.toInt() and (0xFF)
                val hexStr = Integer.toHexString(hex)
                if (hexStr.length == 1) {
                    this.append("0").append(hexStr)
                } else {
                    this.append(hexStr)
                }
            }
            this.toString()
        }
        //转成16进制后是32字节
        return result
    }

    /**
     * 描述：打开并安装文件.
     *
     * @param context the context
     * @param file    apk文件路径
     */
    fun installApk(context: Context, file: File) {
        val intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.action = Intent.ACTION_VIEW
        intent.setDataAndType(
            Uri.fromFile(file),
            "application/vnd.android.package-archive"
        )
        context.startActivity(intent)
    }

    /**
     * 描述：卸载程序.
     *
     * @param context     the context
     * @param packageName 包名
     */
    fun uninstallApk(context: Context, packageName: String) {
        val intent = Intent(Intent.ACTION_DELETE)
        val packageURI = Uri.parse("package:$packageName")
        intent.data = packageURI
        context.startActivity(intent)
    }
}